<?php

namespace App\Http\Controllers;
use GuzzleHttp\Client as GuzzleClient;
use Goutte\Client;
use App\Http\Controllers\Controller;
use JonnyW\PhantomJs\Client as jClient;
use App\Repositories\ArtistRankRepositoryEloquent;
use App\Repositories\ArtistProductionRepositoryEloquent;
use App\Repositories\ImgListRepositoryEloquent;
use Illuminate\Http\Request;

class CrawController extends Controller
{
    /**
     * @var ArtistRankRepositoryEloquent
     */
    protected $artist_repository;
    protected $artist_production_repository;
    protected $img_list_repository;

    public function __construct(ArtistRankRepositoryEloquent $repository, ArtistProductionRepositoryEloquent $production,
                                ImgListRepositoryEloquent $img_list){
        $this->artist_repository = $repository;
        $this->artist_production_repository = $production;
        $this->img_list_repository = $img_list;
    }
    /**
     *
     * @author   ljx
     * @date 2017-08-26
     * @param string $url   请求地址
     * @return null
     *
     **/
    public function av() {
        $url = 'http://www.javlibrary.com/cn/';
        $guzzleClient = new GuzzleClient([
            // Base URI is used with relative requests
            //'base_uri' => 'http://www.javlibrary.com/cn/',
            // You can set any number of default request options.
            'timeout'  => 10.0,
            'proxy' => 'tcp://192.168.1.111:10800'
        ]);

        $goutteClient = new Client();
        $goutteClient->setClient($guzzleClient);
        //采集排行榜数据
        $crawler = $goutteClient->request('GET', $url.'star_mostfav.php');
        $data = $crawler->filter('div.starbox > div.searchitem');
        $av_rank = $data->each(function ($node, $i) {
            $av_info = $node->filter('img')->extract(['src','title'])[0];
            return [
                'rank' => $node->filter('h3')->text(),
                'artist' => $av_info[1],
                'avatar' => $av_info[0],
                'url' => $node->filter('a')->extract('href')[0],
                'artist_'
            ];
        });
        //插入数据库
        $result = $this->artist_repository->updateOrCreate(
            [
                'id' => date('Ymd'),
            ], [
                'id' => date('Ymd'),
                'rank' => json_encode($av_rank)
            ]
        );
        //作品集
        foreach ($av_rank as &$value) {
            $crawler = $goutteClient->request('GET', $url.$value['url']);
            $tmp = $crawler->filter('div.video');
            $production = $tmp->each(function($node, $i) {
                return [
                    $node->filter('div.id')->text(),
                    $node->filter('div.title')->text(),
                    substr($node->filter('img')->extract('src')[0],2)
                ];
            });
            $value['production_list'] = $production;
            $this->artist_production_repository->updateOrCreate(
                [
                    'artist' => $value['artist'],
                ], [
                    'artist' => $value['artist'],
                    'last_production' => json_encode($production)
                ]
            );
            sleep(1);
        }
        return response()->json($av_rank);
    }

    /**
     * 采集无聊图
     * @author   ljx
     * @date 2017-08-30
     * @param string $url   请求地址
     * @return null
     *
     **/
    public function boring(Request $request) {
        $page_num = $request->input('page_num',10);
        $url = 'http://jandan.net/pic/';
        $guzzleClient = new GuzzleClient([
            'timeout'  => 10.0
        ]);
        $goutteClient = new Client();
        $goutteClient->setClient($guzzleClient);
        $crawler = $goutteClient->request('GET', $url);
        $star_page = (int)$crawler->filter('div.cp-pagenavi > a')->text();
        if($star_page <= 0) {
            return response()->json(['msg' => '页码获取失败']);
        }
        $star_page +=1;
        for($page = $star_page-$page_num;$page < $star_page;$page++) {
            //采集排行榜数据
            $crawler = $goutteClient->request('GET', $url . 'page-'.$page.'#comments');
            //获取图片列表
            $data = $crawler->filter('ol.commentlist > li');
            $data->each(function ($node, $i) {
                $uinque = $node->extract('id')[0];
                $uinque = explode('-', $uinque);
                if (isset($uinque[1])) {
                    $uinque = $uinque[1];
                }
                $count = $node->filter('div.text > p > img')->count();
                if($count > 1) {
                    $content['src'] = $node->filter('div.text > p > img')->each(function($img_node, $i){
                        return $img_node->extract('src')[0];
                    });
                }elseif($count == 1) {
                    $img = $node->filter('div.text > p > img')->extract(['src', 'org_src']);
                    $img = $img[0];
                    $content['src'] = $img[0];
                    if (!empty($img[1])) {
                        $content['gif_src'] = $img[1];
                    }
                }else {
                    return false;
                }
                $like_number_node = $node->filter('div.jandan-vote > span.tucao-like-container > span');
                $unlike_number_node = $node->filter('div.jandan-vote > span.tucao-unlike-container > span');
                $like_number = $like_number_node->count() ? $like_number_node->text() : 0;
                $unlike_number = $unlike_number_node->count() ? $unlike_number_node->text() : 0;
                //插入数据库
                $result = $this->insertBoreData('jandan-' . $uinque, [
                    'type' => !empty($content['gif_src']) ? 1 : 2, //1=gif，2=图片
                    'content' => json_encode($content),
                    'praise' => $like_number,
                    'disdain' => $unlike_number,
                    'cate_id' => 1
                ]);
            });
        }exit;
    }
    /**
     * 妹子图
     * @author   ljx
     * @date 2017-09-03
     * @param string $url   请求地址
     * @return null
     *
     **/
    public function amaze(Request $request) {
        $page_num = $request->input('page_num',10);
        $url = 'http://jandan.net/ooxx/';
        $guzzleClient = new GuzzleClient([
            'timeout'  => 10.0
        ]);
        $goutteClient = new Client();
        $goutteClient->setClient($guzzleClient);
        $crawler = $goutteClient->request('GET', $url);
        $star_page = (int)$crawler->filter('div.cp-pagenavi > a')->text();
        if($star_page <= 0) {
            return response()->json(['msg' => '页码获取失败']);
        }
        $star_page +=1;
        for($page = $star_page-$page_num;$page < $star_page;$page++) {
            //采集排行榜数据
            $crawler = $goutteClient->request('GET', $url . 'page-'.$page.'#comments');
            //获取图片列表
            $data = $crawler->filter('ol.commentlist > li');
            $data->each(function ($node, $i) {
                $uinque = $node->extract('id')[0];
                $uinque = explode('-', $uinque);
                if (isset($uinque[1])) {
                    $uinque = $uinque[1];
                }
                //获取楼层的图片
                $count = $node->filter('div.text > p > img')->count();
                if($count > 1) {
                    $content['src'] = $node->filter('div.text > p > img')->each(function($img_node, $i){
                        return $img_node->extract('src')[0];
                    });
                }elseif($count == 1) {
                    $img = $node->filter('div.text > p > img')->extract(['src', 'org_src']);
                    $img = $img[0];
                    $content['src'] = $img[0];
                    if (!empty($img[1])) {
                        $content['gif_src'] = $img[1];
                    }
                }else {
                    return false;
                }
                $like_number_node = $node->filter('div.jandan-vote > span.tucao-like-container > span');
                $unlike_number_node = $node->filter('div.jandan-vote > span.tucao-unlike-container > span');
                $like_number = $like_number_node->count() ? $like_number_node->text() : 0;
                $unlike_number = $unlike_number_node->count() ? $unlike_number_node->text() : 0;
                //插入数据库
                $result = $this->insertBoreData('jandan-' . $uinque, [
                    'type' => !empty($content['gif_src']) ? 1 : 2, //1=gif，2=图片
                    'content' => json_encode($content),
                    'praise' => $like_number,
                    'disdain' => $unlike_number,
                    'cate_id' => 2
                ]);
            });
        }exit;
    }
    /**
     * 插入图片列表
     * @author   ljx
     * @date 2017-09-02
     * @param string $url   请求地址
     * @return null
     *
     **/
    public function insertBoreData($unique_sign, $data) {
        $this->img_list_repository->updateOrCreate(['unique_sign' => $unique_sign],[
            'unique_sign' => $unique_sign,
            'cate_id' => $data['cate_id'],
            'type' => $data['type'],
            'content' => $data['content'],
            'praise' => $data['praise'],
            'disdain' => $data['disdain'],
            'status' => 0,
            'created_at' => time()
        ]);
    }
    public function mockWebKit() {
        $client = jClient::getInstance();
        //这一步非常重要，务必跟服务器的phantomjs文件路径一致
        $client->getEngine()->setPath('/usr/local/bin/phantomjs');
        $request  = $client->getMessageFactory()->createRequest();
        $response = $client->getMessageFactory()->createResponse();
        $client->getEngine()->addOption("--proxy=192.168.1.111:10800");

        $link = 'http://www.javlibrary.com/cn/star_mostfav.php';
        //设置请求方法
        $request->setMethod('GET');
        $request->setDelay('10');
        //设置请求连接
        $request->setUrl($link);
        //发送请求获取响应
        $client->send($request, $response);
        //输出抓取内容
        echo $response->getContent();
        //获取内容后的处理
        exit;
    }
}
